<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="汽车" prop="vehicleId">
        <el-select v-model="queryParams.vehicleId" placeholder="请选择汽车" clearable>
          <el-option
            v-for="item in vehicles"
            :key="item.vehicleId"
            :label="item.manufacturer + ' ' + item.model"
            :value="item.vehicleId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker
          v-model="daterangeCreateTime"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="更新时间">
        <el-date-picker
          v-model="daterangeUpdateTime"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="创建者" prop="createBy">
        <el-input
          v-model="queryParams.createBy"
          placeholder="请输入创建者"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="维修状态" prop="state">
        <el-select v-model="queryParams.state" placeholder="请选择维修状态" clearable>
          <el-option
            v-for="dict in dict.type.repair_request"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="电话号码" prop="phone">
        <el-input
          v-model="queryParams.phone"
          placeholder="请输入电话号码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['repair:accendant:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['repair:accendant:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="repairList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="汽车" align="center" prop="vehicleId" />
      <el-table-column label="维修原因" align="center" prop="reason" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="更新时间" align="center" prop="updateTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.updateTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="维修状态" align="center" prop="state">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.repair_request" :value="scope.row.state"/>
        </template>
      </el-table-column>
      <el-table-column label="电话号码" align="center" prop="phone" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-setting"
            v-if="scope.row.state === 1"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['repair:accendant:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-if= "scope.row.state === 2"
            v-hasPermi="['repair:accendant:edit','repair:accendant:getStoreMaterial','repair:accendant:query','repair:accendant:add']"
          >修改</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改报修申请对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <div v-show="dialogForm"
           v-for="(item,index) in List"
           :key="index"
           style="position: relative"
      >
        <el-form ref="form" :model="{form}" label-width="80px">
            <el-row>
              <el-col :span="4">
                <el-button icon="el-icon-minus"
                           @click="deleteItem(item,index)"
                           circle
                           style="font-size:5px;   position: absolute; left:1px"/>
              </el-col>
              <el-col :span="10">
                <el-form-item label="材料">
                  <el-select v-model="item.materialId" clearable placeholder="请选择">
                    <el-option
                      v-for="item2 in form"
                      :key="item2.material.materialId"
                      :label="item2.material.materialName"
                      :value="item2.material.materialId">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="10">
                <el-form-item label="数量">
                  <el-input-number
                    v-model.number="item.quantity"
                    :min="1"
                    :max="10"
                    controls-position="right"
                  />
                </el-form-item>
              </el-col>
            </el-row>
        </el-form>
      </div>

      <div slot="footer" style="display: flex;justify-content: space-between">
        <el-button type="primary" @click="addItem"><i class="el-icon-plus" style="margin-right: 5px"></i>添加材料</el-button>
        <div>
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
// import {listRepair, getRepair, delRepair, addRepair, updateRepair, hasCar} from "@/api/repair/repair";
import {listRepair, getRepair, updateRepair, getStoreMaterial, addMaterial} from "@/api/repair/fix";

export default {
  name: "Fix",
  dicts: ['repair_request'],
  data() {
    return {

      // 车
      vehicles: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 报修申请表格数据
      repairList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 电话号码时间范围
      daterangeCreateTime: [],
      // 电话号码时间范围
      daterangeUpdateTime: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        vehicleId: null,
        reason: null,
        createTime: null,
        updateTime: null,
        createBy: null,
        state: null,
        phone: null,
      },
      // 表单参数
      form: {},
      // 所选的材料种类及数量
      List: [],
      //是否再增加一个材料输入
      dialogForm:false,
      //提交的维修单的ID
      submitRepairedId:'',
      //暂时存储一行的数据
      temp:{}
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询报修申请列表 */
    getList(){
      listRepair(this.queryParams).then(response => {
        this.repairList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },

    addItem() {
      this.dialogForm = true
      this.List.push({
        materialName:'',
        quantity:''
      })
    },

    deleteItem(item, index) {
      console.log(index)
      this.List.splice(index, 1)
    },

    // getList() {
    //   hasCar().then(response => {
    //
    //     this.vehicles = []
    //     if(response)
    //     {
    //       this.vehicles.push(response)
    //     }
    //   });
    //   this.loading = true;
    //   this.queryParams.params = {};
    //   if (null != this.daterangeCreateTime && '' != this.daterangeCreateTime) {
    //     this.queryParams.params["beginCreateTime"] = this.daterangeCreateTime[0];
    //     this.queryParams.params["endCreateTime"] = this.daterangeCreateTime[1];
    //   }
    //   if (null != this.daterangeUpdateTime && '' != this.daterangeUpdateTime) {
    //     this.queryParams.params["beginUpdateTime"] = this.daterangeUpdateTime[0];
    //     this.queryParams.params["endUpdateTime"] = this.daterangeUpdateTime[1];
    //   }
    //   listRepair(this.queryParams).then(response => {
    //     this.repairList = response.rows;
    //     this.total = response.total;
    //     this.loading = false;
    //   });
    // },
    // 取消按钮
    cancel() {
      this.open = false;
      console.log(this.List)
      this.List = []
      // this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        repairId: null,
        vehicleId: null,
        reason: null,
        createTime: null,
        updateTime: null,
        createBy: null,
        updateBy: null,
        state: null,
        phone: null,
        repairBy: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangeCreateTime = [];
      this.daterangeUpdateTime = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.repairId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      // 修改维修状态，从未维修到正在维修
      if (row.state === 1){
        row.state = 2
        this.reset()
        const repairId = row.repairId
        getRepair(repairId).then(response => {
          this.form = response.data;
          this.form.state = 2
          updateRepair(this.form).then(response => {
            this.$modal.msgSuccess("修改成功")
            this.getList()
          })
        });
      }else {
        this.temp = row
        this.submitRepairedId = row.repairId
        getStoreMaterial().then(respond => {
          this.form = respond.rows
          this.open = true
          this.title = "维修清单"
        })
        // this.reset();
        // const repairId = row.repairId || this.ids
        // getRepair(repairId).then(response => {
        //   this.form = response.data;
        //   this.open = true;
        //   this.title = "维修单";
        // });
      }
    },
    /** 提交按钮 */
    submitForm() {
      if (this.List.length !== 0){
        //将数据中的materialName属性删除
        let newList = JSON.parse(JSON.stringify(this.List))
        newList.map(e => {delete e.materialName})
        //为数组中添加repair_id
        newList.forEach(item => {
          item.repair_id = this.submitRepairedId
        })
        this.loading = true;
        addMaterial(newList).then(res => {
          this.$modal.msgSuccess('添加成功')
          this.List = []
          this.open = false
          this.loading = false

          //修改状态，从正在维修转换为已完成
          this.temp.state = 3
          const repairId = this.temp.repairId
          getRepair(repairId).then(response => {
            this.form = response.data;
            this.form.state = 3
            updateRepair(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.getList()
            })
          });
        })
      }
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('repair-request/repair/export', {
        ...this.queryParams
      }, `fix_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
